from django.shortcuts import render, redirect, HttpResponse
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from www.forms.account import Login, SmsLogin, SendSms
from www import models
from django_redis import get_redis_connection
from utils.ronglian_sms import send_sms as send_sms_ronglian, get_code

def login(request):
    """ 用户名密码登录 """
    if request.method == 'GET':
        form = Login()
        # print(request.path)  # /login/
        request
        return render(request, "login.html", {"form": form})

    # 表单验证
    form = Login(data=request.POST)
    if not form.is_valid():
        return render(request, "login.html", {"form": form})

    # 数据库验证
    data_dict = form.cleaned_data
    role = data_dict.pop("role")  # 返回的就是role
    if role == "1":
        # 管理员
        user_obj = models.Administrator.objects.filter(**data_dict).filter(active=1).first()
    else:
        # 用户
        user_obj = models.Customer.objects.filter(**data_dict).filter(active=1).first()
    if not user_obj:
        form.add_error("password", "用户名或密码错误")
        return render(request, "login.html", {"form": form})

    # 保存用户信息到session
    mapping = {"1": "ADMIN", "2": "CUSTOMER"}
    request.session["user_info"] = {
        "role": mapping[role],
        "id": user_obj.id,
        "username": user_obj.username
    }

    # 跳转到家目录
    return redirect('home')


def sms_login(request):
    """ 短信登录 """
    if request.method == 'GET':
        form = SmsLogin()
        return render(request, "login.html", {"form": form})

    # 表单验证
    form = SmsLogin(data=request.POST)
    if not form.is_valid():
        return render(request, "login.html", {"form": form})

    # 验证校验码
    role = form.cleaned_data["role"]
    mobile = form.cleaned_data["mobile"]
    code = form.cleaned_data["code"]
    # 从redis中获取code
    conn = get_redis_connection("default")
    redis_code = conn.get(mobile)
    if not redis_code or not redis_code.decode("utf-8") == code:  # 1.得先判断有没有redis_code   2.redis_code是字节串，需解码为字符串
        form.add_error("code", "验证码错误或失效")
        return render(request, "login.html", {"form": form})
    # 验证成功后，清除
    conn.delete(mobile)

    # 保存用户信息到session
    if role == "1":
        # 管理员
        user_obj = models.Administrator.objects.filter(mobile=mobile).filter(active=1).first()
    else:
        # 用户
        user_obj = models.Customer.objects.filter(mobile=mobile).filter(active=1).first()
    mapping = {"1": "ADMIN", "2": "CUSTOMER"}
    request.session["user_info"] = {
        "role": mapping[role],
        "id": user_obj.id,
        "username": user_obj.username
    }

    # 跳转页面
    return redirect("home")

@csrf_exempt
def send_sms(request):
    """ 发送短信 """
    # 手机号格式校验
    form = SendSms(data=request.POST)
    if not form.is_valid():
        return JsonResponse({"status": False, "msg": form.errors})

    # 校验手机号是否存在(可以放到clean_mobile钩子方法中，用的是raise ValidationError)
    mobile = form.cleaned_data["mobile"]
    role = form.cleaned_data["role"]
    if role == "1":
        # 管理员
        exists = models.Administrator.objects.filter(mobile=mobile).filter(active=1).exists()
    else:
        # 用户
        exists = models.Customer.objects.filter(mobile=mobile).filter(active=1).exists()
    if not exists:
        # 用户
        return JsonResponse({"status": False, "msg": {"mobile": ["手机号不存在"]}})# 注意：msg格式需要这样写

    # 发短信
    code = 1234
    # code = get_code(4)
    # ret = send_sms_ronglian(
    #     mobile='13162358424',  # 这个手机号必须在你在容联云中填写的那个3个测试手机号中
    #     datas=(code, 2),  # 元组的第一个参数是4位的验证码,注意免费测试的只支持发送4位的验证码，不支持6位的，第二个参数是短信模板中替换为：请于{2}分钟内正确输入
    #     tid=1  # 这个模板id目前测试阶段固定为1
    # )
    # # 发送失败
    # if not ret:
    #     return JsonResponse({"status": False, "msg": {"mobile": ["短信发送失败"]}})

    # 发送成功，写入redis
    conn = get_redis_connection("default")
    conn.set(mobile, code, ex=2*60)  # 需设置过期时间 & 验证一次后，清除
    return JsonResponse({"status": True, "msg": "发送成功"})


def logout(request):
    """ 退出 """
    request.session.clear()
    return redirect("login")

def home(request):
    """ 首页 """
    username = request.user_info["username"]
    return render(request, "home.html", {"username": username})

